package com.sright.bcard.common.service.share.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author peter
 * @description jwt工具类
 * @date 2020/5/14
 */
public class JWTUitls {

    private static final String JWT_USERID_KEY = "userid";
    private static final String JWT_USERNAME_KEY = "username";

    private static final Logger logger = LoggerFactory.getLogger(JWTUitls.class);

    /**
     * 密钥
     */
    private static final String SECRET = "com.sright.vcloud.user.login.nice";
    /**
     * 过期时间
     **/
    public static final long EXPIRATION = 3600 * 24 * 365L;//单位为秒

    /**
     * 为用户生成token
     * @param: userId
     * @param: name
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @author jinxuebin
     * @date 2020/5/25 10:40 上午
    */
    public static Map<String, Object> createUserToken(String userId, String name) {
        if (userId == null || name == null) {
            return null;
        }
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION * 1000);
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create()
                .withHeader(map)// 添加头部
                //可以将基本信息放到claims中
                .withClaim(JWT_USERID_KEY, userId)
                .withClaim(JWT_USERNAME_KEY, name)
                .withExpiresAt(expireDate) //超时设置,设置过期的日期
                .withIssuedAt(new Date()) //签发时间
                .sign(Algorithm.HMAC256(SECRET)); //SECRET
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("expires", expireDate.getTime() / 1000); //除1000兼容老版本
        return result;
    }

    /**
     * @description: 验证token
     * @params: [token]
     * @return: 用户id
     * @author: jinxuebin
     * @time: 2020/5/14 10:36 上午
     */
    public static Long validateToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            logger.error(e.getMessage());
            logger.error("token解码异常");
            //解码异常则抛出异常
            return 0L;
        }
        Map<String, Claim> map = jwt.getClaims();
        if (map.containsKey(JWT_USERID_KEY)) {
            Claim claim = map.get(JWT_USERID_KEY);
            return Long.parseLong(claim.asString());
        }
        return 0L;
    }

}
